<template>
  <el-dialog :model-value="modelValue" @close="close()" draggable :title="title" width="50%">
    <el-form :model="roleForm" label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="名称" prop="roleName">
            <el-input placeholder="名称" v-model="roleForm.roleName" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="启用" prop="enabled">
            <el-switch v-model="roleForm.isEnabled" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="内置管理员" prop="isAdmin">
            <el-switch v-model="roleForm.isAdmin" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close()">取消</el-button>
        <el-button type="primary" @click="saveForm()">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import RoleApi, { Role } from "@/api/sys/role";
import { EditEnum } from "@/enums/EditEnum";

const props = defineProps({
  modelValue: Boolean,
  info: Object,
  type: Number,
  title: String,
});

const roleForm = ref<Role>();
watch(
  () => props.info,
  (newInfo: Role, oldInfo: Role) => {
    if (newInfo) {
      roleForm.value = newInfo;
    }
  },
  {
    deep: true,
    immediate: true,
  }
);

const emits = defineEmits(["update:modelValue", "success"]);
const saveForm = async () => {
  const { success, message } = await RoleApi[EditEnum[props.type]](roleForm.value);
  if (success) {
    emits("success");
    ElNotification({
      title: message,
      type: "success",
    });
    close();
  } else {
    ElNotification({
      title: message,
      type: "error",
    });
  }
};

const close = () => {
  emits("update:modelValue", false);
};
</script>
